--
-- @Author:      name
-- @DateTime:    2018-03-30 23:05:48
-- @Description: 消息的处理

local skynet = require "skynet"
local cluster = require "skynet.cluster"
local log = require "Logger"
local config = require "configquery"
local ProtoLoader = require "ProtoLoader"
local NodeMessage = require "NodeMessage"

local cjson = require "cjson"

local MessageHandler = class("MessageHandler")

--构造函数
function MessageHandler:ctor(message_dispatch)
	
	self.svr_id = skynet.getenv("svr_id") --节点名
	self.proto_file = skynet.getenv("proto_config") --proto文件路径	
	self.proto_loader = ProtoLoader.new() --proto加载

	self.message_dispatch = message_dispatch
	self.node_message = NodeMessage.new()
	self.robot_list = {}

	self:register()
end

--注册本服务里的消息
function MessageHandler:register()
	--启动
	self.message_dispatch:registerSelf('start', handler(self,self.start))
	self.message_dispatch:registerSelf('login_req', handler(self,self.onLoginReq))

	self.message_dispatch:registerSelf('add_robot_to_game', handler(self,self.addRobotToGame))

end


function MessageHandler:start()

	print("___proto_file_",self.proto_file)
	local pbc_env = self.proto_loader:init(self.proto_file, {'common','game','gate','web','zone','hall',})
	-- local svr_config = config.setting_cfg["robotserver"]
	
	--初始化
	self.node_message:initProto(pbc_env)

	--skynet控制台
	-- local debug_port = skynet.getenv("debug_port")
	-- skynet.newservice("debug_console", debug_port)
	-- --定义变量
	-- local server_port_t = tonumber(skynet.getenv("server_port_t")) or 0
	-- local server_port_ws = tonumber(skynet.getenv("server_port_ws")) or 0
	-- local max_client = tonumber(skynet.getenv("max_client")) or 1024

	-- --启动socket gate
	-- local conf = {
	-- 		port = server_port_t,
	-- 		maxclient = max_client,
	-- 		nodelay = true,
	-- 	}		
	-- local gate = skynet.newservice("gate")
	-- -- log.debug('_____________manager open socket gate port:'.. conf.port)
	-- skynet.call(gate, "lua", "open", conf)

	-- --启动websocket gate
	-- local ws_conf = {
	-- 		port = server_port_ws,
	-- 		maxclient = max_client,
	-- 		nodelay = true,
	-- 	}
	-- local wsgate = skynet.newservice("wsgate")
	-- -- log.debug('_____________manager open websocket gate port:'.. ws_conf.port)
	-- skynet.call(wsgate, "lua", "open", ws_conf)

	-- --socket消息处理服务
	-- local gate_service
	-- for i = 1, 1 do
	-- 	gate_service = skynet.newservice("gate_service")		
	-- 	self.message_session:addSessionService(gate_service)
	-- 	skynet.call(gate_service, 'lua', 'init', pbc_env)
	-- end
	-- self.gate_service = gate_service

	--数据库,加入需要的表
	-- local tables = {
	-- 	{name="user", pk='user_id',key='user_id',  }, --no_use_redis=true
	-- 	{name="robot_node", pk='id',key='name',  }, 
		
	-- }
 	-- self.node_message:callDbProxy("load_tables",tables)
 	

 	-- print("______res__",res)
 	-- self:createRobot(50)

 	skynet.fork(function()
 		skynet.sleep( 800 )
 		-- self:addRobotToGame()
 	end)
end

-- 生成一些机器人帐号
function MessageHandler:createRobot(create_num)
	local num = os.time()
	local function func()	
		num = num + 1
		local username = "robot_"..num
		local user = {
			-- domain_id = data.domain_id,
			-- device_type = "contos",
			register_time = timeToString(os.time()),
			merchant_id = 0,
			username = username,
			password = "123456",
			nickname = username,			
			-- face_id = 1,		
			mac_addr = num,
			is_robot = 1,	
		}
		local res = self.node_message:callDbProxy("add_user",user)
		local sql = string.format("select user_id from user where username='%s'",username)
		local res = self.node_message:callDbMySql(sql)
		res = res[1]
		print("______res__",res)
		self.node_message:callDbProxy("add_trade_wallet",{user_id=res.user_id})
	end
	skynet.fork(function()
		for i=1, create_num do 
			print("_______创建机器人___",i)
			func()
			skynet.sleep(30)
		end
	end)
end

-- 取一个机器人
function MessageHandler:getRobotUser()
 	local robot_user = self.node_message:callDbRedis("rpop", {"robot_user"})
	if not robot_user or #robot_user==0 then 
		--取完redis的从mysql加载
		local sql = "select user_id, username, password, gold from user where is_robot=1 and online=0"
		local sql = "select u.user_id, u.username, u.password, w.balance from user u, trade_wallet w where is_robot=1 and online=0 and u.user_id=w.user_id "
		local res = self.node_message:callDbMySql(sql)
		if not next(res) then 
			print("____没有离线的机器人____")
			return 
		end
		for k, v in pairs(res) do 
		 	-- 把取到机器人放到redis 队列里
		 	local str = cjson.encode(v)		 	
		 	self.node_message:callDbRedis("lpush", {"robot_user", str})		 	
		end
		robot_user = self.node_message:callDbRedis("rpop", {"robot_user"})
	end
	-- print("___robot_user__",robot_user)	
	if not robot_user or #robot_user==0 then 
		return 
	end
	return cjson.decode(robot_user)
end

-- 机器人加金币
function MessageHandler:addRobotGold(server_id, robot)
	-- 机器人金钱不足时自动增加
	local sql = string.format("select s.server_id, s.type, s.name, s.max_client, g.* from system_server_node s, game_room g where s.game_id=g.game_id  and s.server_id=%d" , server_id )
	local game_config = self.node_message:callDbProxy("executeMySql", sql) 
		if game_config then game_config = game_config[1] end	

	local balance = tonumber(robot.balance)
	if balance > game_config.max_enter_score then 
		balance = game_config.max_enter_score
	elseif balance < game_config.min_enter_score then 
		balance = math.random(game_config.min_enter_score, game_config.max_enter_score)
	end
	if balance ~= tonumber(robot.balance) then 
		-- print("____________robot.gold____________________",robot, gold)
		--更新到数据库
		self.node_message:callDbProxy("update_trade_wallet", {balance = balance}, {{user_id = robot.user_id}})
	end	
end

--请求增加机器人
function MessageHandler:addRobotToGame(data)
	print("___addRobotToGame______",data)
	local robot = self:getRobotUser()
	if not robot then
		return -- 没有机器人用
	end
	self:addRobotGold(data.server_id, robot)
	local info = {
		robot_type = data.game_code,
		server_id = data.server_id,
		game_id = data.game_id,
		desk_id = data.desk_id,
		group_id = data.group_id,		
		robot_name = robot.username,
		robot_password = robot.password,
	}
	print("__111____addRobotToGame___",data, robot)
	local node = "robot_"..data.game_code
	if not self.robot_list[data.game_code] then
		-- 机器人没连上来
		return
	end
	self.node_message:sendNode(node, ".proxy", "add_robot_to_game", info)
end


function MessageHandler:onLoginReq(data)
	print("_____onLoginReq__",data)
	self.robot_list[data.name] = 1

    -- 加载到集群配置
    local cluster_name = data.cluster_name
    local cluster_addr = data.cluster_addr 
    local cluster_config = {
        [cluster_name] = cluster_addr,
    }
    cluster.reload(cluster_config)	
end



return MessageHandler